package mvc.filter.filters.Security;

import mvc.filter.PreHandlerInterceptor;
import mvc.pojo.Handler;
import mvc.utils.URLUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class SecurityInterceptor implements PreHandlerInterceptor {
    @Override
    public boolean preHandler(HttpServletRequest req, HttpServletResponse resp, Object object) throws IOException {
        if (object instanceof Handler){
            Handler handler = (Handler) object;
            Set<String> filters = new HashSet<>();

            boolean isMethodAnnotationed = handler.getMethod().isAnnotationPresent(Security.class);
            boolean isTypeAnnotationed = handler.getController().getClass().isAnnotationPresent(Security.class);
            if (!isMethodAnnotationed && !isTypeAnnotationed){
                return true;
            }
            Map<String, Object> map = URLUtils.getParameter(req.getQueryString());
            if (!map.containsKey("username")){
                resp.getWriter().write("access failed");
                return false;
            }
            if (isMethodAnnotationed){
                String[] names = handler.getMethod().getAnnotation(Security.class).value();
                if (!Arrays.asList(names).contains(map.get("username").toString())){
                    resp.getWriter().write("access failed");
                    return false;
                }
            }
            if (isTypeAnnotationed){
                String[] names = handler.getController().getClass().getAnnotation(Security.class).value();
                if (!Arrays.asList(names).contains(map.get("username").toString())){
                    resp.getWriter().write("access failed");
                    return false;
                }
            }
            return true;
        }else {
            return true;
        }
    }
}
